package com.dream.dao.impl;



import com.dream.dao.DormitoryDao;
import com.dream.pojo.Dormitory;
import com.dream.utils.DBUtil;

import java.util.ArrayList;
import java.util.List;

public class DormitoryDaoImpl implements DormitoryDao {

    @Override
    public List<Dormitory> list() {
        return DBUtil.commonQuery(Dormitory.class, "select * from dormitory");
    }

    @Override
    public Dormitory findById(String dormitoryId) {
        ArrayList<Dormitory> users = DBUtil.commonQuery(Dormitory.class, "select * from dormitory where dormitory_id=?",
                dormitoryId);
        if(users.size()>0){
            return users.get(0);
        }
        return null;
    }

    @Override
    public long totalCount(String dormitoryName) {
        String sql = "select count(dormitory.dormitory_id) FROM dormitory where 1=1";
        StringBuilder sb = new StringBuilder(sql);
        if(dormitoryName!=null && !"".equals(dormitoryName)){
            sb.append(" and dormitory.dormitory_name like '%"+dormitoryName+"%'");
        }
        return DBUtil.queryCount(sb.toString());
    }

    @Override
    public List<Dormitory> list(String dormitoryName, long pageIndex, long pageSize) {
        String sql = "select * FROM dormitory where 1=1";
        StringBuilder sb = new StringBuilder(sql);
        if(dormitoryName!=null && !"".equals(dormitoryName)){
            sb.append(" and dormitory.dormitory_name like '%"+dormitoryName+"%'");
        }
        sb.append(" limit ?,?");
        return DBUtil.commonQuery(Dormitory.class, sb.toString(),(pageIndex-1)*pageSize,pageSize);
    }

    @Override
    public int add(Dormitory dormitory) {
        try {
            DBUtil.commonUpdate("insert into dormitory values (?,?,?)",
                    dormitory.getDormitoryId(),
                    dormitory.getDormitoryName(),
                    dormitory.getRemark());
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public int update(Dormitory dormitory) {
        try {
            DBUtil.commonUpdate("update dormitory set dormitory_name=?,remark=? where dormitory_id=?",
                    dormitory.getDormitoryName(),
                    dormitory.getRemark(),
                    dormitory.getDormitoryId());
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public int deleteById(String dormitoryId) {
        try {
            DBUtil.commonUpdate("delete from  dormitory where dormitory_id=?", dormitoryId);
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
}
